<template>
    <div>
        <van-form ref="registerForm">
            <span class="field_title">手机号</span>
            <van-field
                    v-model="form.phone"
                    label=""
                    placeholder="请输入手机号"
                    clearable
                    :rules="phoneRules"
            />
            <span class="field_title">姓名</span>
            <van-field
                    v-model="form.studentName"
                    label=""
                    placeholder="请输入您的姓名"
                    clearable
                    :rules="[{ required: true, message: '' }]"
            >
            </van-field>
            <span class="field_title">身份证号</span>
            <van-field
                    v-model="idCard"
                    label=""
                    placeholder="请输入身份证号"
                    clearable
                    :rules="idcardRules"
            />
            <span class="field_title">性别</span>
            <van-field
                    v-model="form.sex"
                    label=""
                    placeholder="性别通过身份证号码自动识别"
                    disabled
            />

            <span class="field_title">邀请码</span>
            <van-field
                    v-model="form.invitationCode"
                    label=""
                    placeholder="请输入邀请码"
                    clearable
                    :disabled = "invitationCode != ''"
            />
            <div>
                <van-divider>身份信息</van-divider>
            </div>
            <span class="field_title">证件照（电子版JPG格式，长宽比例为4:3，尺寸：480*640，文件大小不超过20K，照片必须清晰完整。成像区上下要求头上部空1/10，头部占7/10，肩部占1/5；左右各空1/10）</span>
            <div style="display: flex;padding: 15px;">
                <van-uploader v-model="certificateFileList" :after-read="certificateAfterRead" :before-read="certificateBeforeRead" upload-icon="plus"  :max-count="1"/>
            </div>

            <span class="field_title">身份证正面：正面截齐 20kb-60kb</span>
            <div style="display: flex;padding: 15px;">
                <van-uploader v-model="idCardFrontFileList" :after-read="file=>idCardFrontAfterRead(file,1)" :before-read="file=>idCardBeforeRead(file,1)" upload-icon="plus"  :max-count="1"/>
            </div>
            <span class="field_title">身份证反面：反面截齐 20kb-60kb</span>
            <div style="display: flex;padding: 15px;">
                <van-uploader v-model="idCardVersoFileList" :after-read="idCardVersoAfterRead" :before-read="file=>idCardBeforeRead(file,0)" upload-icon="plus"  :max-count="1"/>
            </div>
            <div>
                <van-divider>毕业证书信息</van-divider>
            </div>
            <span class="field_title">学历毕业证照片（初中/高中/大专/大学） 30-100kb</span>
            <div style="display: flex;padding: 15px;">
                <van-uploader v-model="highSchoolCertificateFileList" :after-read="highSchoolCertificateAfterRead" :before-read="file=>highSchoolCertificateBeforeRead(file)" upload-icon="plus" :max-count="1"/>
            </div>
           <!-- <span class="field_title">毕业学校</span>
            <van-field
                    v-model="form.diplomaSchool"
                    label=""
                    placeholder="请输入毕业学校"
                    clearable
                    :rules="[{ required: true, message: '' }]"
            />-->
            <div>
                <van-divider>报考学校信息</van-divider>
            </div>
            <van-field
                    v-model="fieldValue"
                    is-link
                    readonly
                    label="报考工种"
                    placeholder="请选择工种"
                    @click="show = true"
            />
            <van-popup v-model="show" round position="bottom">
                <van-cascader
                        v-model="cascaderValue"
                        title="请选择所在工种"
                        :options="options"
                        @close="show = false"
                        @finish="onFinish"
                />
            </van-popup>
            <div v-if="fee">
                <span class="field_title">补贴金额：{{fee}}元</span>
                <span class="field_title">报考要求：{{registerSchoolRequirement}}</span>
            </div>


            <div style="margin: 16px;text-align: center;">
                <van-button round block type="info" native-type="submit" v-if="!isSubmit" @click="handleRegister"  class="btn">立 即 提 交</van-button>
                <van-loading type="spinner" color="#1989fa" v-else/>
            </div>
        </van-form>
    </div>
</template>

<script>
    const KB = 1024;
    import {listQualificationCertificateList,getSpecialty,addStudent} from '@/api/school'
    import {Toast} from 'vant'
    import {identityIdCard,validPhone} from '@/utils/validate'
    export default {
        name: "registerIndex",
        data(){
            return {
                invitationCode: '',
                idCard: '',
                fee: undefined,
                registerSchoolRequirement: undefined,
                durationTime: undefined,
                show: false,
                fieldValue: '',
                cascaderValue: '',
                // 选项列表，children 代表子选项，支持多级嵌套
                options: [
                    {
                        text: '长春大学',
                        value: '1',
                        children: [
                            {
                                text: '专升本',
                                value: '1',
                                children: [
                                    { text: '软件工程', value: '1' },
                                    { text: '计算机科学技术', value: '2' },
                                    { text: '会计学', value: '3' }
                                ]
                            },
                            { text: '高起专', value: '2' },
                            { text: '高起本', value: '3' },
                        ],
                    },
                    {
                        text: '工业大学',
                        value: '2',
                        children: [{ text: '专升本', value: '320100' }],
                    },
                ],
                schoolShow: false,
                levelShow: false,
                specialtyShow: false,
                schoolColumns: [
                    {
                        id:1 ,
                        name:'长春工业大学'
                    },
                    {
                        id:2 ,
                        name:'长春大学'
                    },
                    {
                        id:3 ,
                        name:'长春工程学院'
                    },
                    {
                        id:4 ,
                        name: '通化师范'
                    }
                ],
                levelColumns: ['高起专', '专生本', '高起本'],
                specialtyColumns: ['工商管理', '软件工程', '会计学'],
                timeShow: false,
                userLoginInfo: undefined,
                isSubmit: false,
                radio: '1',
                minDate: new Date(2000, 0, 1),
                maxDate: new Date(),
                currentDate: new Date(),
                form: {
                    studentName: '',// 名字
                    nationality: '',//民族
                    idCard: '',// 身份证号
                    sex: '', // 性别
                    phone: '', // 电话号
                    invitationCode: '',
                    diplomaNo: '', //毕业学校编号
                    diplomaSchool: '', //毕业学校名称
                    diplomaGraduationTime: '', // 毕业时间
                    registerSpecialtyFeeId: '', // 报考专业
                    registerSpecialtyFeeName: '', // 报考层次
                },
                phoneRules: [
                    { required: true, message: ''},
                    // 自定义校验规则
                    {
                        validator: value => {
                            return validPhone(value)
                        },
                        message: '请输入正确格式的手机号码',
                        trigger: 'onBlur'
                    }
                ],
                idcardRules: [
                    { required: true, message: ''},
                    // 自定义校验规则
                    {
                        validator: value => {
                            return identityIdCard(value)
                        },
                        message: '请输入正确格式的身份证号',
                        trigger: 'onBlur'
                    }
                ],
                fileList: [
                    /*{
                        url: 'https://img01.yzcdn.cn/vant/leaf.jpg',
                        status: 'uploading',
                        message: '上传中...',
                    },*/
                    /*{
                        url: 'https://img01.yzcdn.cn/vant/tree.jpg',
                        status: 'failed',
                        message: '上传失败',
                    },*/
                    /*{
                        url: 'https://img01.yzcdn.cn/vant/tree.jpg',
                        status: 'success',
                        message: '上传成功',
                    },*/
                ],
                certificateFileList: [],// 二寸证件照
                idCardFrontFileList: [],// 身份证正面
                idCardVersoFileList: [],// 身份证反面
                evidentiaryMaterialFileList: [],// 证明材料
                highSchoolCertificateFileList: [],// 高中毕业证
            }
        },
        methods: {
            // 全部选项选择完毕后，会触发 finish 事件
            onFinish({ selectedOptions }) {
                this.show = false;
                this.fieldValue = selectedOptions.map((option) => option.text).join('/');
                let value = selectedOptions.map((option) => option.value).join('-');
                console.log("值是：",value);
                console.log(this.fieldValue);
                // 获得专业id
                let valueArr = value.split('-');
                let spId = valueArr[valueArr.length-1];
                console.log("专业id",spId);
                this.form.registerSpecialtyFeeId = spId;
                // 查学费
                getSpecialty(spId).then(resp=>{
                    console.log("专业信息",resp);
                    if(resp.code == 200){
                        this.fee = resp.data.fee;
                        this.registerSchoolRequirement = resp.data.remark;
                    }
                });
            },
            onSpecialtyChange(picker, value, index) {
                // Toast(`当前值：${value}, 当前索引：${index}`);
            },
            onSpecialtyCancel() {
                this.specialtyShow = ! this.specialtyShow
            },
            onSpecialtyConfirm(value, index) {
                this.specialtyShow = ! this.specialtyShow
                this.form.registerSpecialtyFeeName = `${value}`
            },
            onLevelConfirm(value, index) {
                this.levelShow = ! this.levelShow
                // Toast(`当前值：${value}, 当前索引：${index}`);
                this.form.registerSchoolLevelName = `${value}`
            },
            onLevelChange(picker, value, index) {
                // Toast(`当前值：${value}, 当前索引：${index}`);
            },
            onLevelCancel() {
                this.levelShow = ! this.levelShow
            },
            onSchoolConfirm(value, index) {
                this.schoolShow = ! this.schoolShow
                // Toast(`当前值：${value}, 当前索引：${index}`);
                this.form.registerSchoolName = this.schoolColumns[index].school_name
                this.form.registerSchoolId = this.schoolColumns[index].school_id
            },
            onSchoolChange(picker, value, index) {
                // Toast(`当前值：${value}, 当前索引：${index}`);
            },
            onSchoolCancel() {
                // Toast('取消');
                this.schoolShow = ! this.schoolShow
            },
            calcColon(val){ // 添加冒号
                if(val){
                    val = ': '+val;
                }
                return val
            },
            handleTime(){
                this.timeShow = ! this.timeShow;
            },
            confirmTime(){
                this.handleTime();
                console.log('currentDate',this.currentDate)
                this.form.diplomaGraduationTime = this.currentDate.getFullYear()+'-'+(Number(this.currentDate.getMonth()) + 1)+'-'+this.currentDate.getDate()
                console.log("毕业时间",this.form.diplomaGraduationTime);
            },
            cancelTime(){
                console.log('cancelTime')
            },
            calcSex(){
                let isIdcard = identityIdCard(this.form.idCard);
                console.log(isIdcard);
                if(isIdcard){
                    if (parseInt(this.form.idCard.substr(16, 1)) % 2 == 1) {
                        this.form.sex = '男';
                    } else {
                        this.form.sex = '女';
                    }
                }else{
                    this.form.sex = '不详';
                }
            },
            handleRegister(){
                console.log("证明材料",this.evidentiaryMaterialFileList);
                console.log(this.evidentiaryMaterialFileList.length);
                this.$refs.registerForm.validate().then(()=>{
                    if(this.form.registerSpecialtyFeeId == ''){
                       return this.dialogNotifyError("请选择报考学校专业")
                    }
                    this.isSubmit = true
                    let formData = new FormData();
                    /*
                    * name: undefined,// 名字
                    nationality: undefined,//民族
                    idCard: undefined,// 身份证号
                    sex: undefined, // 性别
                    phone: undefined, // 电话号
                    recommenedcode: undefined,
                    diplomaGraduationTime: undefined, //毕业时间
                    registerSchoolId: undefined, //毕业学校id
                    registerSpecialtyFeeId: undefined, // 报考专业
                    registerSpecialtyFeeName: undefined, // 报考层次
                    diplomaGraduationTime: undefined, //毕业时间
                    diplomaNo: undefined, //毕业学校id
                    diplomaSchool: undefined, //毕业学校名称
                    diplomaGraduationTime: new Date(), // 毕业时间
                    *
                    * */
                    formData.append("projectId","2")// 资格证书报名
                    formData.append("studentName",this.form.studentName)
                    formData.append("nationality",this.form.nationality)
                    if( ! this.form.idCard){
                        this.form.idCard = this.idCard;
                    }
                    formData.append("idCard",this.form.idCard)
                    if(! this.form.sex){
                        this.calcSex();
                        formData.append("sex",this.form.sex)
                    }else{
                        formData.append("sex",this.form.sex)
                    }
                    formData.append("phone",this.form.phone)
                    formData.append("sysUserId",this.form.invitationCode)
                    formData.append("diplomaGraduationTime",this.form.diplomaGraduationTime)
                    formData.append("diplomaNo",this.form.diplomaNo)
                    formData.append("diplomaSchool",this.form.diplomaSchool)
                    formData.append("registerSchoolProfessionId",this.form.registerSpecialtyFeeId)
                    // 证件照
                    if(this.certificateFileList.length > 0){
                        this.certificateFileList.forEach(item=>{
                            formData.append("certificateFile",item.file)
                        })
                    }
                    // 身份证正面
                    if(this.idCardFrontFileList.length > 0){
                        this.idCardFrontFileList.forEach(item=>{
                            formData.append("idCardFrontFile",item.file)
                        })
                    }
                    // 身份证反面
                    if(this.idCardVersoFileList.length > 0){
                        this.idCardVersoFileList.forEach(item=>{
                            formData.append("idCardVersoFile",item.file)
                        })
                    }
                    // 前置学历 highSchoolCertificateFile
                    if(this.highSchoolCertificateFileList.length > 0){
                        this.highSchoolCertificateFileList.forEach(item=>{
                            formData.append("highSchoolCertificateFile",item.file)
                        })
                    }
                    // 证明材料
                    if(this.evidentiaryMaterialFileList.length > 0){
                        this.evidentiaryMaterialFileList.forEach(item=>{
                            formData.append("evidentiaryMaterialFiles",item.file)
                        })
                    }
                    addStudent(formData).then(response => {
                        console.log("添加信息返回：",response);
                        this.isSubmit = false
                        if(response.code == 200){
                            Toast("报名成功")
                            this.$router.push({name: 'signUpQueryIndex',query: this.form.idCard}) // 根据身份证查询该信息
                        }
                    }).catch((error) => {
                        if(error) console.log(error)
                    }).finally(()=>{
                        this.isSubmit = false
                    })
                    /*const headers = {
                        'Content-Type': 'application/json;charset=utf-8',
                        'token': this.userLoginInfo.token
                    }

                    let url = this.requestUrl+"/h5protal/user/add_info";
                    console.log("完善信息访问地址：",url);
                    axios.post(url, data, {
                        headers: headers
                    }).then((response) => {
                        console.log("添加信息返回：",response);
                        let data = response.data;
                        if(data.code == 0){
                            // 存token
                            this.setToken(this.userLoginInfo.token);
                            this.$router.push("/");
                        }else if(data.code == 280002){
                            Toast(data.msg);
                        }

                    }).catch((error) => {
                       if(error) console.log(error)
                    })*/
                }).catch(()=>{
                    //验证失败
                    this.isSubmit = false
                    console.log("验证失败");
                    return this.dialogNotifyError("请补充信息之后再提交");
                })
            },
            // 证件照片处理
            certificateAfterRead(file) {
                file.status = 'uploading';
                file.message = '上传中...';

                /*setTimeout(() => {
                    file.status = 'failed';
                    file.message = '上传失败';
                }, 500);*/
                console.log("file文件信息",file.file);
                console.log("证件照片处理文件列表：",this.certificateFileList);
                // 此时可以自行将文件上传至服务器
                let formData = new FormData();
                if (file.constructor != Array) {
                    console.log("不是数组");
                    console.log(file.file);
                    formData.append("file", file.file);
                    console.log(formData);
                } else {
                    console.log("是数组");
                    file.forEach(element => {
                        formData.append("file", element.file);
                    });
                }
                /*upload_info_nurse(this.userLoginInfo.userId,formData).then(response=>{
                    console.log(response);
                    file.status = 'success';
                    file.message = '上传成功';
                }).catch(err=>{
                    console.log(err);
                    file.status = 'failed';
                    file.message = '上传失败';
                })*/

                setTimeout(()=>{
                    file.status = 'success';
                    file.message = '上传成功';
                },500)

            },
            certificateBeforeRead(file){
                console.log("文件信息",file);
                if (file.type !== 'image/jpeg') {
                    Toast('请上传 jpg 格式图片');
                    return false;
                }
                let fileSize = file.size;
                if(fileSize >= 20*KB){
                    Toast('大小不能超过20KB');
                    return false;
                }
                return true;
            },
            // 身份证正面处理
            idCardFrontAfterRead(file,type) { // 身份证正面
                console.log("type",type);
                file.status = 'uploading';
                file.message = '上传中...';
                /*setTimeout(() => {
                    file.status = 'failed';
                    file.message = '上传失败';
                }, 500);*/
                console.log("file文件信息",file.file);
                console.log("身份证正面文件列表：",this.idCardFrontFileList);
                // 此时可以自行将文件上传至服务器
                let formData = new FormData();
                if (file.constructor != Array) {
                    console.log("不是数组");
                    console.log(file.file);
                    formData.append("file", file.file);
                    console.log(formData);
                } else {
                    console.log("是数组");
                    file.forEach(element => {
                        formData.append("file", element.file);
                    });
                }
                /*upload_idcard(this.userLoginInfo.userId,formData).then(response=>{
                    console.log(response);
                    file.status = 'success';
                    file.message = '上传成功';
                }).catch(err=>{
                    console.log(err);
                    file.status = 'failed';
                    file.message = '上传失败';
                })*/

                setTimeout(()=>{
                    file.status = 'success';
                    file.message = '上传成功';
                },500)

            },
            idCardBeforeRead(file,type){
                console.log("文件信息",file);
                console.log("上传的身份证标识",type);
                if (file.type !== 'image/jpeg') {
                    Toast('请上传jpg格式图片');
                    return false;
                }
                let fileSize = file.size;
                if(fileSize > 60*KB){
                    Toast('不能超过60KB');
                    return false;
                }
                if(fileSize < 20*KB){
                    Toast('不能小于20KB');
                    return false;
                }
                return true;
            },
            // 身份证反面
            idCardVersoAfterRead(file) {
                file.status = 'uploading';
                file.message = '上传中...';
                /*setTimeout(() => {
                    file.status = 'failed';
                    file.message = '上传失败';
                }, 500);*/
                console.log("file文件信息",file.file);
                console.log("身份证反面文件列表：",this.idCardVersoFileList);
                // 此时可以自行将文件上传至服务器
                let formData = new FormData();
                if (file.constructor != Array) {
                    console.log("不是数组");
                    console.log(file.file);
                    formData.append("file", file.file);
                    console.log(formData);
                } else {
                    console.log("是数组");
                    file.forEach(element => {
                        formData.append("file", element.file);
                    });
                }
                /*upload_idcard_back(this.userLoginInfo.userId,formData).then(response=>{
                    console.log(response);
                    file.status = 'success';
                    file.message = '上传成功';
                }).catch(err=>{
                    console.log(err);
                    file.status = 'failed';
                    file.message = '上传失败';
                })*/
                setTimeout(()=>{
                    file.status = 'success';
                    file.message = '上传成功';
                },500)
            },
            // 正面材料上传
            evidentiaryMaterialBeforeRead(file){
                if (file.type !== 'image/jpeg') {
                    Toast('请上传jpg格式图片');
                    return false;
                }
              return true;
            },
            evidentiaryMaterialAfterRead(file){
                file.status = 'uploading';
                file.message = '上传中...';
                /*setTimeout(() => {
                    file.status = 'failed';
                    file.message = '上传失败';
                }, 500);*/
                console.log("file文件信息",file.file);
                console.log("证明材料列表：",this.evidentiaryMaterialFileList);
                // 此时可以自行将文件上传至服务器
                let formData = new FormData();
                if (file.constructor != Array) {
                    console.log("不是数组");
                    console.log(file.file);
                    formData.append("file", file.file);
                    console.log(formData);
                } else {
                    console.log("是数组");
                    file.forEach(element => {
                        formData.append("file", element.file);
                    });
                }
                setTimeout(()=>{
                    file.status = 'success';
                    file.message = '上传成功';
                },500)
            },
            // 高中毕业证
            highSchoolCertificateBeforeRead(file){
                console.log("文件信息",file);
                if ( file.type !== 'image/jpeg') {
                    Toast('请上传jpg格式图片');
                    return false;
                }
                let fileSize = file.size;
                if(fileSize > 100*KB){
                    Toast('不能超过100KB');
                    return false;
                }
                if(fileSize < 30*KB){
                    Toast('不能小于30KB');
                    return false;
                }
                return true;
            },
            highSchoolCertificateAfterRead(file){
                file.status = 'uploading';
                file.message = '上传中...';
                console.log("file文件信息",file.file);
                console.log("高中毕业证列表：",this.highSchoolCertificateFileList);
                // 此时可以自行将文件上传至服务器
                let formData = new FormData();
                if (file.constructor != Array) {
                    console.log("不是数组");
                    console.log(file.file);
                    formData.append("file", file.file);
                    console.log(formData);
                } else {
                    console.log("是数组");
                    file.forEach(element => {
                        formData.append("file", element.file);
                    });
                }
                setTimeout(()=>{
                    file.status = 'success';
                    file.message = '上传成功';
                },500)
            }
        },
        created(){
            this.$store.commit('setTitleName','资格证书报名')
            let invitationCode = this.getUrlArgusString("invitationCode");
            if(invitationCode != null){
                // 保存到会话里
                sessionStorage.setItem("invitationCode",invitationCode);
            }
            if(sessionStorage.getItem("invitationCode")){
                // 赋值 解决切换页面跳转问题
                this.form.invitationCode = sessionStorage.getItem("invitationCode");
                this.invitationCode = sessionStorage.getItem("invitationCode");
            }
            listQualificationCertificateList().then(resp=>{
                console.log("学校信息",resp);
                if(resp.code == 200){
                    this.schoolColumns = resp.data;
                    this.options = resp.data;
                }
            });
        },
        watch:{
            idCard(idCard){
                let isIdcard = identityIdCard(idCard);
                this.form.sex = '';
                if(isIdcard){
                    this.form.idCard = idCard
                    if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
                        this.form.sex = '男';
                        console.log('男')
                    } else {
                        this.form.sex = '女';
                        console.log('女')
                    }
                }
            }
        }
    }
</script>

<style scoped>
    .roleDiv{padding: 15px;}
    .field_title{display:block;text-align: left;padding: 15px 15px 0px 15px;}
    .btn{background: #CCCCCC;border: none;border-radius: 0px;color: black;}
</style>
